#ifndef STATISTICS_COLLECTOR_H
#define STATISTICS_COLLECTOR_H

#include <stdint.h>
#include <stdbool.h>

#ifdef __cplusplus
extern "C" {
#endif

// Forward declarations
typedef struct statistics_collector statistics_collector_t;
typedef struct table_stats table_stats_t;
typedef struct column_stats column_stats_t;

// Table statistics structure
struct table_stats {
    uint32_t table_id;
    char* table_name;
    uint64_t row_count;
    uint64_t page_count;
    uint64_t total_size;
    double avg_row_size;
    uint64_t last_updated;
    
    // Column statistics
    column_stats_t* columns;
    uint32_t column_count;
};

// Column statistics structure  
struct column_stats {
    uint32_t column_id;
    char* column_name;
    uint64_t distinct_count;
    uint64_t null_count;
    double selectivity;
    
    // Histogram data
    struct {
        char** values;
        uint64_t* frequencies;
        uint32_t bucket_count;
    } histogram;
    
    // Min/Max values for range queries
    char* min_value;
    char* max_value;
};

// Statistics collector main structure
struct statistics_collector {
    table_stats_t** tables;
    uint32_t table_count;
    uint32_t capacity;
    
    // Configuration
    bool auto_update_enabled;
    uint32_t update_threshold;  // Update stats after N modifications
    uint32_t histogram_buckets; // Default histogram bucket count
    
    // Runtime counters
    uint64_t queries_processed;
    uint64_t updates_performed;
};

// Core API functions
statistics_collector_t* stats_collector_create(void);
void stats_collector_destroy(statistics_collector_t* collector);

// Table statistics management
table_stats_t* stats_get_table_stats(statistics_collector_t* collector, uint32_t table_id);
int stats_update_table_stats(statistics_collector_t* collector, uint32_t table_id);
int stats_add_table(statistics_collector_t* collector, uint32_t table_id, const char* table_name);

// Column statistics management  
column_stats_t* stats_get_column_stats(statistics_collector_t* collector, uint32_t table_id, uint32_t column_id);
int stats_update_column_stats(statistics_collector_t* collector, uint32_t table_id, uint32_t column_id);

// Query processing statistics
int stats_hash_query(statistics_collector_t* collector, const char* query_hash);
int stats_record_query(statistics_collector_t* collector, 
                     const char* query_hash,
                     uint64_t execution_time_ms,
                     uint64_t rows_examined,
                     uint64_t rows_returned);
double stats_estimate_selectivity(statistics_collector_t* collector, uint32_t table_id, uint32_t column_id, const char* operator, const char* value);

// Utility functions
int stats_export_to_file(statistics_collector_t* collector, const char* filename);
int stats_import_from_file(statistics_collector_t* collector, const char* filename);
void stats_print_summary(statistics_collector_t* collector);

#ifdef __cplusplus
}
#endif

#endif // STATISTICS_COLLECTOR_H